<template>
  <div class="permission-container">
    <div class="left-panel">
      <div class="project-panel">
        <div v-for="project in projects" :key="project.id" class="project-item"
             :class="{ active: project.systemCode === selectedProjectId }" @click="selectProject(project.systemCode)">
          <el-icon >
            <component :is="project.icon"/>
          </el-icon>    {{ project.systemName }}
        </div>
      </div>
    </div>

    <div class="module-panel">
      <div v-if="selectedProjectId">
        <el-button class="add-module-btn" type="primary" @click="showAddModuleDialog(null)">
          新建模块
        </el-button>
        <el-tree
            style="max-width: 600px"
            :data="treeData"
            :props="defaultProps"
            node-key="id"
            :default-expand-all="true"
            :highlight-current="false"
            @node-click="handleNodeClick"
            ref="treeRef"
            class="full-width-tree">

          <template #default="{ node, data }">
            <div
                class="custom-tree-node"
                @mouseenter="currentHoverNode = data.id"
                @mouseleave="currentHoverNode = null">

              <el-icon >
                <component :is="data.icon"/>
              </el-icon>

              <span class="node-label">{{ node.label }}</span>

              <span v-show="currentHoverNode === data.id" class="node-actions">
            <el-button size="small" @click.stop="handleAdd(data)">新增</el-button>
            <el-button size="small" @click.stop="handleEdit(data)">修改</el-button>
            <el-button size="small" type="danger" @click.stop="handleDelete(data)">删除</el-button>
          </span>
            </div>
          </template>
        </el-tree>
      </div>
      <div v-else class="empty-text">请选择左侧项目</div>
    </div>

    <!-- 新增模块对话框 -->
    <el-dialog v-model="dialogVisible" title="新建模块" width="30%">
      <el-form-item label="模块名称" prop="permissionName">
        <el-input v-model="moduleForm.permissionName" placeholder="请输入模块名称"/>
      </el-form-item>

      <el-form-item label="优先级" prop="orderNum">
        <el-input-number v-model="moduleForm.orderNum" :min="0"/>
      </el-form-item>

      <el-form-item label="图标" prop="icon">
        <el-select v-model="moduleForm.icon" placeholder="请选择图标" filterable clearable>
          <el-option v-for="icon in elementIcons" :key="icon" :value="icon" :label="icon">
            <div style="display: flex; align-items: center; gap: 10px;">
              <el-icon>
                <component :is="ElementPlusIcons[icon]"/>
              </el-icon>
              <span>{{ icon }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="path">
        <el-input v-model="moduleForm.path" placeholder="请输入地址（如 /dashboard）"/>
      </el-form-item>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddModule">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {ElMessage} from 'element-plus';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import {getSystemList} from '@/api/system';
import {getModulesByProjectId, addPermission, transformData,getModulesByCode} from '@/api/permission';

export default {
  name: 'PermissionList',
  components: {
    ...ElementPlusIconsVue
  },
  data() {
    return {
      projects: [],
      currentHoverNode: null,// 当前悬停的节点ID
      selectedProjectId: null,
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      ElementPlusIcons: ElementPlusIconsVue, // 将图标集合暴露给模板
      elementIcons: Object.keys(ElementPlusIconsVue),
      treeData: [],
      dialogVisible: false,
      moduleForm: {
        permissionName: '',
        permissionCode: '',
        systemCode: this.selectedProjectId,
        parentId: null,
        orderNum: 0,
        icon: '',
        path: ''
      },
      allModules: []
    };
  },
  methods: {
    async fetchSystems() {
      try {
        const res = await getSystemList({});
        this.projects = res.data.list || [];
      } catch (error) {
        console.error('获取系统列表失败:', error);
        ElMessage.error('获取系统列表失败');
      }
    },

    async selectProject(projectId) {
      this.selectedProjectId = projectId;
      await this.loadProjectModules({
        systemCode: projectId
      });
    },

    async loadProjectModules(data) {
      try {
        const res = await getModulesByProjectId(data);
        // 假设这是从后端获取的原始数据数组 rawData
        console.log(res.data)
        // 使用转换函数处理数据并赋值给 treeData
        this.treeData = transformData(res.data);
        console.log("处理完成的树结构",this.treeData)
        this.collectAllModules();
      } catch (error) {
        console.error('获取模块数据失败:', error);
        ElMessage.error('获取模块数据失败');
      }
    },
    showAddModuleDialog(parentId) {
      // const firstNode = this.treeData[0];
      this.moduleForm = {
        permissionName: '',
        // parentId: firstNode ? firstNode.id : null,
        parentId: parentId,
        orderNum: 0,
        systemCode: this.selectedProjectId,
        icon: '',
        path: '',
        permissionType: '1'
      };
      this.dialogVisible = true;
    },
    showEditModuleDialog(data) {
      getModulesByCode({permissionCode:data.id}).then(res=>{
        this.moduleForm = res.data
        console.log(res)
      }).catch(error=>{
        ElMessage.error(error)
      })
      this.dialogVisible = true;
    },
    async handleAddModule() {
      if (!this.moduleForm.permissionName) {
        ElMessage.warning('请输入模块名称');
        return;
      }

      console.log(this.moduleForm)
      await addPermission(this.moduleForm).then(res => {
        if (res.code === '200') {
          ElMessage.success('新增成功！');
        }
      })
      this.dialogVisible = false;
      await this.loadProjectModules({
        systemCode: this.selectedProjectId
      })
    },
    findNode(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) return node;
        if (node.children) {
          const found = this.findNode(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },
    collectAllModules() {
      this.allModules = [];
      this.flattenModules(this.treeData);
    },
    flattenModules(nodes) {
      nodes.forEach(node => {
        this.allModules.push({id: node.id, label: node.label});
        if (node.children && node.children.length > 0) {
          this.flattenModules(node.children);
        }
      });
    },
    handleAdd(data) {
      this.showAddModuleDialog(data.id)
    },
    handleEdit(data) {
      // 确保这个方法存在且有实现
      this.showEditModuleDialog(data)
      console.log('Edit', data);
      // 你的编辑逻辑
    },
    handleDelete(data) {
      // 确保这个方法存在且有实现
      console.log('Delete', data);
      // 你的删除逻辑
    },
    handleNodeClick(data) {
      console.log('节点点击:', data);
    }
  },
  mounted() {
    this.fetchSystems();
  }
};
</script>

<style scoped>
.permission-container {
  display: flex;
  height: 100%;
  padding: 20px;
}

.left-panel {
  width: 220px;
  display: flex;
  flex-direction: column;
}

.project-panel {
  flex: 1;
  border-right: 1px solid #ebeef5;
  padding-right: 10px;
  margin-bottom: 10px;
  overflow-y: auto;
}

.module-panel {
  flex: 1;
  padding-left: 20px;
  overflow-y: auto;
}

.project-item {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
  text-align: center;
}

.project-item.active {
  background-color: #409eff;
  color: white;
}

.empty-text {
  color: #999;
  font-size: 16px;
  text-align: center;
  margin-top: 50px;
}

.add-module-btn {
  width: 100px;
  margin-top: 10px;
}

/* 使整个节点区域可悬浮 */
.full-width-tree .el-tree-node__content {
  position: relative; /* 为绝对定位按钮提供参照 */
  height: 36px; /* 固定高度，确保整个区域可点击 */
}

/* 自定义节点容器 */
.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;
  padding-right: 10px;
}

/* 节点标签样式 */
.node-label {
  flex: 1;
  padding-left: 4px;
}

/* 操作按钮容器 */
.node-actions {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

/* 按钮样式 */
.node-actions .el-button {
  margin-left: 5px;
  padding: 5px 8px;
}

/* 悬停效果 */
.full-width-tree .el-tree-node__content:hover {
  background-color: #f5f7fa;
}
</style>
